<template>
  <div class="mt-5">
    <a-form layout="inline" :model="formState">
      <a-form-item label="机构名称">
        <a-tree-select
          v-model:value="formState.comId"
          :tree-data="companyOptions"
          allow-clear
          style="width: 300px"
          tree-node-filter-prop="label"
          placeholder="请选择机构名称"
        />
      </a-form-item>
      <a-form-item label="管辖小区">
        <a-select
          v-model:value="formState.menuName"
          :options="options"
          style="width: 200px"
          placeholder="请输入管辖小区"
        ></a-select>
      </a-form-item>
      <a-form-item label="关键字">
        <a-input
          v-model:value="formState.nickName"
          placeholder="请输入关键字"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="onSearch">搜索</a-button>
      </a-form-item>
      <a-form-item>
        <a-button>重置</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" :icon="h(PlusOutlined)" @click="visible = true"
          >新增</a-button
        >
      </a-form-item>
    </a-form>
    <div class="mt-5">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'action'">
            <a-space>
              <a-button type="link">修改</a-button>
              <a-button type="link">批量操作</a-button>
              <a-button type="link">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
    <a-drawer
      v-model:open="visible"
      title="新增人员权限"
      placement="right"
      @close="visible = false"
      size="large"
    >
      <a-form layout="inline" class="mb-3">
        <a-form-item label="人员">
          <a-tree-select
            v-model:value="operator"
            tree-data-simple-mode
            allow-clear
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="selectList"
            placeholder="请选择人员"
            :load-data="onLoadData"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSubmit">提交</a-button>
        </a-form-item>
      </a-form>
      <div style="height: 800px">
        <a-transfer
          v-model:target-keys="targetKeys"
          class="h-full"
          :data-source="dataSource"
          :render="(item) => item.title"
          :show-select-all="false"
          :list-style="{ height: '100%', overflow: 'auto' }"
        >
          <template #children="{ direction, selectedKeys, onItemSelect }">
            <a-tree
              v-if="direction === 'left'"
              block-node
              checkable
              check-strictly
              :tree-data="TransferData"
              :load-data="onLoadTransferData"
              :checked-keys="[...selectedKeys, ...targetKeys]"
              @check="
                (_, props) => {
                  onChecked(
                    props,
                    [...selectedKeys, ...targetKeys],
                    onItemSelect,
                  );
                }
              "
              @select="
                (_, props) => {
                  onChecked(
                    props,
                    [...selectedKeys, ...targetKeys],
                    onItemSelect,
                  );
                }
              "
            />
          </template>
        </a-transfer>
      </div>
    </a-drawer>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, h } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import {
  getSubCompanyApi,
  getFindVillage,
  getCurrentCompanyIdApi,
  getVillageListApi,
  getInsert,
} from '#/api';
import { getOperatorApi } from '#/api/core/statistical';
import { message } from 'ant-design-vue';
import type { TransferProps, TreeProps } from 'ant-design-vue';
interface TreeNode {
  value: string;
  id: string;
  level: string;
  label: string;
  key?: string; // 添加 key 属性
  children?: TreeNode[];
}
const formState = reactive({
  comId: undefined,
  menuName: undefined,
  nickName: undefined,
});
const targetKeys = ref<string[]>([]);
const visible = ref(false);
const operator = ref(undefined);
const TransferData = ref([]);
const formatTreeData = (data: any[]): TreeNode[] => {
  return data.map((item: any) => {
    const node: TreeNode = {
      value: item.levelID || item.id, // 确保 value 存在且唯一
      id: item.id,
      level: item.level,
      label: item.name,
      key: item.levelID || item.id, // key 和 value 保持一致
    };

    if (item.children && item.children.length > 0) {
      const children = formatTreeData(item.children);
      if (children.length > 0) {
        node.children = children;
      }
    }
    return node;
  });
};
const companyOptions = ref<TreeNode[]>([]);
const getSubCompany = () => {
  getSubCompanyApi().then((res: any) => {
    console.log(res);
    companyOptions.value = formatTreeData([{ ...res.data }]);
    console.log(companyOptions.value);
    // console.log();
  });
};
getSubCompany();
const options = ref([
  {
    value: 'jack',
    label: 'Jack',
  },
  {
    value: 'lucy',
    label: 'Lucy',
  },
  {
    value: 'tom',
    label: 'Tom',
  },
]);
const columns = [
  {
    title: '人员',
    dataIndex: 'nickName',
    key: 'nickName',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '操作时间',
    dataIndex: 'updatetime',
    key: 'updatetime',
    align: 'center',
  },
  {
    title: '管辖小区',
    dataIndex: 'villageInfo',
    key: 'villageInfo',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
  },
];
const dataSource = ref<TransferProps['dataSource']>([]);
const tableData = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  const query = {
    comId: formState.comId,
    // menuName:formState.menuName,
    nickName: formState.nickName,
  };
  getFindVillage(pagination.current, pagination.pageSize, query).then(
    (res: any) => {
      console.log(res);
      tableData.value = res.data.data;
      pagination.total = res.data.total;
    },
  );
};

const selectList = ref([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.userId ? item.userId : item.userId,
            title: item.name,
            key: item.name ? item.name : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const onLoadTransferData = (treeNode: any) => {
  return new Promise<void>((resolve) => {
    if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
      resolve();
      return;
    }
    getVillageListApi(treeNode.dataRef.key).then((res: any) => {
      if (!res.data.data || res.data.data.length === 0) {
        treeNode.dataRef.isLeaf = true; // 如果数据为空，则设置为叶子节点
        resolve();
        return;
      }
      const children = res.data.data.map((item: any) => ({
        value: item.id,
        key: item.id,
        title: item.name,
        isLeaf: false, // 第三级为叶子节点
      }));
      treeNode.dataRef.children = children;
      TransferData.value = [...TransferData.value]; // 触发视图更新

      // 更新dataSource以包含新加载的数据
      dataSource.value = flattenTreeData(TransferData.value);

      resolve();
    });
  });
};

// 将树形数据转换为扁平化的dataSource
const flattenTreeData = (treeData: any[]): TransferProps['dataSource'] => {
  const result: TransferProps['dataSource'] = [];

  const traverse = (nodes: any[]) => {
    nodes.forEach((node) => {
      result.push({
        key: node.key,
        title: node.title,
        disabled: false,
      });
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    });
  };

  traverse(treeData);
  return result;
};

const getTransfer = () => {
  getCurrentCompanyIdApi().then((res: any) => {
    // console.log(res);
    TransferData.value = res.data.data.map((item: any) => {
      return {
        value: item.id,
        key: item.id,
        title: item.name,
        children: [],
        isLeaf: false, // 第一级不是叶子节点
      };
    });

    // 更新dataSource
    dataSource.value = flattenTreeData(TransferData.value);

    if (res.data.data.length > 0) {
      getVillageListApi(res.data.data[0].id).then((p: any) => {
        const data = p.data.data.map((item: any) => {
          return {
            value: item.id,
            key: item.id,
            title: item.name,
            children: [],
            isLeaf: false, // 第二级不是叶子节点
          };
        });
        TransferData.value[0].children = data;

        // 重新更新dataSource
        dataSource.value = flattenTreeData(TransferData.value);
        console.log(TransferData.value);
      });
    }
  });
};
getTransfer();
function isChecked(
  selectedKeys: (string | number)[],
  eventKey: string | number,
) {
  return selectedKeys.indexOf(eventKey) !== -1;
}
const onChecked = (
  e: Parameters<TreeProps['onCheck']>[1] | Parameters<TreeProps['onSelect']>[1],
  checkedKeys: string[],
  onItemSelect: (n: any, c: boolean) => void,
) => {
  const { eventKey } = e.node;
  onItemSelect(eventKey, !isChecked(checkedKeys, eventKey));
};
const onSubmit = () => {
  console.log(dataSource.value, targetKeys.value);
  const data = {
    userId: operator.value,
    villageId: targetKeys.value,
  };
  getInsert(data).then((res: any) => {
    console.log(res);
    if (res.data.code == 200) {
      visible.value = false;
      message.success('新增成功');
    } else {
      message.error('新增失败');
    }
  });
};
</script>
<style scoped></style>
